package com.dxl.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dxl.base.Result;
import com.dxl.base.Results;
import com.dxl.base.util.ExeOpenFile;
import com.dxl.base.util.MdToHtml;
import com.dxl.system.mapper.ConfigMapper;
import com.dxl.system.mapper.TypeMapper;
import com.dxl.system.model.Config;
import com.dxl.system.model.Groups;
import com.dxl.system.model.Note;
import com.dxl.system.model.Type;
import com.dxl.system.service.GroupsService;
import com.dxl.system.service.LabelService;
import com.dxl.system.service.NoteService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;

/**
 * <b> 首页控制器
 * </b><br><br><i>Description</i> :
 * <br><br>Date: 2019/9/25 ${time}    <br>Author : dxl
 */
@Api(value = "首页接口",tags = {"首页--接口"})
@Controller
public class BeginController {

    @Autowired
    GroupsService groupsService;
    @Autowired
    LabelService labelService;
    @Autowired
    NoteService noteService;
    @Autowired(required = false)
    ConfigMapper configMapper;
    @Autowired(required = false)
    TypeMapper typeMapper;

    /**
     * 跳转到首页
     */
    @GetMapping(value = "/")
    public String index(Model model) {
        PageInfo<Groups> groupList = (PageInfo<Groups>) groupsService.getListByPage(new Groups(),1,20).getData();
        model.addAttribute(groupList);
        return "index";
    }
    /**
     * 获取html的CSS列表---为什么去掉他，项目首页都访问不了????????
     */
    @GetMapping(value = "/selectHtmlCssHtml2")
    public String selectHtmlCssHtml(@RequestParam(value="noteId", required = true) Integer noteId,Model model) {
        return "note/note_select_html_css";
    }
   /**
    * <b> 用程序打开文件
    * </b><br><br><i>Description</i> :
    * @param noteId
    * @return java.lang.String
    * <br><br>Date: 2019/10/3 18:50    <br>Author : dxl
    */
    @ApiOperation(value = "用程序打开文件",notes = "")
    @RequestMapping(value = "/openNote",method = {RequestMethod.POST })
    @ResponseBody
    public Result openNote(@RequestParam(value="noteId", required = true) Integer noteId) {
        Note note = (Note) noteService.getById(noteId).getData();
        Groups groups = (Groups) groupsService.getById(note.getGroupId()).getData();
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.eq("config_key","FileRootPath");
        Config config = configMapper.selectOne(configQueryWrapper);
        if(config == null || config.getConfigKey() == null){
            return Results.failure("系统中无根路径配置，请在数据库中先配置config_key为FileRootPath的记录:(");
        }
        if(config.getConfigValue().substring(config.getConfigValue().length()-1).equals("/")){
            config.setConfigValue(config.getConfigValue().substring(0,config.getConfigValue().length()-1));
        }
        Type type = typeMapper.selectById(note.getTypeId());
        File file = new File(config.getConfigValue()+"/"+groups.getNote()+"file/"+note.getNoteTitle()+"."+note.getTypeSuffix());
        if(!file.exists()){
            return Results.failure("此文件不存在:(");
        }
        try {
            if(type.getExePath() == null || "".equals(type.getExePath().replace(" ",""))){
                ExeOpenFile.openFile(null,config.getConfigValue()+"/"+groups.getNote()+"file/"+note.getNoteTitle()+"."+note.getTypeSuffix());
            }else {
                ExeOpenFile.openFile(type.getExePath(),config.getConfigValue()+"/"+groups.getNote()+"file/"+note.getNoteTitle()+"."+note.getTypeSuffix());
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Results.failure("使用本地程序打开文件失败:(");
        }
        return Results.success();
    }

    /**
     * <b> 渲染note为Html
     * </b><br><br><i>Description</i> :
     * @param noteId
     * @return java.lang.String
     * <br><br>Date: 2019/10/3 18:50    <br>Author : dxl
     */
    @ApiOperation(value = "渲染note为Html",notes = "")
    @RequestMapping(value = "/editNoteToHtml",method = {RequestMethod.POST })
    @ResponseBody
    public Result editNoteToHtml(@RequestParam(value="noteId", required = true) Integer noteId,@RequestParam(value="cssName", required = true) String cssName) {
        Note note = (Note) noteService.getById(noteId).getData();
        Type type = typeMapper.selectById(note.getTypeId());
        if(!type.getIsHtml().equals("是")){
            return Results.failure("该类型不能渲染为html:(");
        }
        Groups groups = (Groups) groupsService.getById(note.getGroupId()).getData();
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.eq("config_key","FileRootPath");
        Config config = configMapper.selectOne(configQueryWrapper);
        if(config == null || config.getConfigKey() == null){
            return Results.failure("系统中无根路径配置，请在数据库中先配置config_key为FileRootPath的记录:(");
        }
        if(config.getConfigValue().substring(config.getConfigValue().length()-1).equals("/")){
            config.setConfigValue(config.getConfigValue().substring(0,config.getConfigValue().length()-1));
        }
        Result result = MdToHtml.mdToHtml(config.getConfigValue()+"/"+groups.getNote()+"file/"+note.getNoteTitle()+"."+note.getTypeSuffix(),cssName,config.getConfigValue()+"/"+groups.getNote()+"html/",note.getNoteTitle());
        return result;
    }

    /**
     * <b> 用程序打开文件html
     * </b><br><br><i>Description</i> :
     * @param noteId
     * @return java.lang.String
     * <br><br>Date: 2019/10/3 18:50    <br>Author : dxl
     */
    @ApiOperation(value = "用程序打开文件html",notes = "")
    @RequestMapping(value = "/openHtml",method = {RequestMethod.POST })
    @ResponseBody
    public Result openHtml(@RequestParam(value="noteId", required = true) Integer noteId) {
        Note note = (Note) noteService.getById(noteId).getData();
        Type type = typeMapper.selectById(note.getTypeId());
        if(!type.getIsHtml().equals("是")){
            Result result = openNote(noteId);
            return result;
        }
        Groups groups = (Groups) groupsService.getById(note.getGroupId()).getData();
        QueryWrapper<Config> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.eq("config_key","FileRootPath");
        Config config = configMapper.selectOne(configQueryWrapper);
        if(config == null || config.getConfigKey() == null){
            return Results.failure("系统中无根路径配置，请在数据库中先配置config_key为FileRootPath的记录:(");
        }
        if(config.getConfigValue().substring(config.getConfigValue().length()-1).equals("/")){
            config.setConfigValue(config.getConfigValue().substring(0,config.getConfigValue().length()-1));
        }
        QueryWrapper<Config> configHtmlQueryWrapper = new QueryWrapper<>();
        configHtmlQueryWrapper.eq("config_key","HtmlExePath");
        Config configHtml = configMapper.selectOne(configHtmlQueryWrapper);
        File file = new File(config.getConfigValue()+"/"+groups.getNote()+"html/"+note.getNoteTitle()+".html");
        if(!file.exists()){
            return Results.failure("请先渲染为html:(");
        }
        try {
            if(configHtml == null ||configHtml.getConfigValue() == null || "".equals(configHtml.getConfigValue().replace(" ",""))){
                ExeOpenFile.openFile(null,config.getConfigValue()+"/"+groups.getNote()+"html/"+note.getNoteTitle()+".html");
            }else {
                ExeOpenFile.openFile(configHtml.getConfigValue(),config.getConfigValue()+"/"+groups.getNote()+"html/"+note.getNoteTitle()+".html");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Results.failure("使用本地程序打开文件失败:(");
        }
        return Results.success("打开成功:)");
    }

}
